const IndexUtils = require('./index')

let instanceRequest = {}

let Route = require('./route')

let {getLastPage} = require('./utils')

const Auth = require('./auth')

export function makeRequest(options = {}) {
  let request = IndexUtils.initRequest()
  // request.loadingTasks = {}
  // request.registerTask = function(id, obj) {
  //   request.loadingTasks[id] = obj
  //   return request
  // }
  // request.unRegisterTask = function(id) {
  //   delete request.loadingTasks[id]
  // }
  request.onFinally = function(requestSelf) {
    console.log('request onFinally', requestSelf)
  }
  request.handleServerErr = function(e) {
    // wx.hideLoading()
    console.log('handleServerErr', e)
    setTimeout(() => {
      wx.hideLoading()
    }, 0)
    let app = getApp()
    app.setToastLock(false)
    if (e && e.response) {
      if (e.response.statusText === 'WX_USER_ABORT') {
        app.showToast('请求异常')
      } else {
        app.showToast('服务器失败')
      }
    }
  }
  request.handleErrCode = function(code, res) {
    let app = getApp()
    console.log('handleErrCode', code, res)

    if (res.request.url.indexOf('register/status') > -1) {
      if (code === 61001 ) {
        // Route.redirectTo('register-form')
        Route.redirectTo('landpage')
      }
      return false
    }

    if (code > 20000) {

      if (code == 50012) {
        // access_token 过期
        // 过期才可以重新请求
        app.requestToken().then(res => {
          if (options && options.onSecond) {
            options.onSecond(res.request)
          }
        })

        return false
      }
      if (code == 50015) {
        // access_token 不合法
        // app.checkIsRegistered()
      }
    }
    return true
  }
  request.shouldCatchErr = function(res) {
    if (res && res.request) {
      console.log('shouldCatchErr', res, res.request.url)
      // if (res.request.url.indexOf('student/register') > -1) {
      //   if (!res || !res.data || !res.data.code ) {
      //     return true
      //   } else {
      //     return res.data.code > 20000 && res.data.code !== 61003
      //   }
      // } else {
      //   return !res || !res.data || !res.data.code || res.data.code > 20000
      // }
      return !res || !res.data || !res.data.code || res.data.code > 20000
    } else {
      return true
    }
  }

  request.handleErrMessage = function (message, err, res, config, context) {
    let app = getApp()
    if (res) {
      let _request = res.request
      let lastPage = getLastPage()
      let allowGo = true

      console.log('handleErrMessage', _request)
      if (lastPage && lastPage.handleErrMessage) {
        allowGo = lastPage.handleErrMessage(message, err, res, config, {
          _request,
          context
        })
      }

      if (!allowGo) {
        return
      }

      setTimeout(() => {
        context.hideLoadingUI()
      }, 1000)


      if (request.handleToastShow) {
        request.handleToastShow(message, err, res, config, context, Auth)
        return
      }

      app.setToastLock(false)
      if (config.mode === 'dev' && !config.forceToast) {
        app.showDevToast(message)
      } else {
        app.showToast(message)
      }
    } else {
      console.error('no res', message, err)
    }
  }

  return request
}

export function getInstance() {
  if (instanceRequest.handleServerErr) {
    return instanceRequest
  }
  try {
    instanceRequest = makeRequest({
      onSecond(request) {
        let app = getApp()
        app.resolveSecondRequest(request)
      }
    })
    return instanceRequest
  } catch (e) {
    console.error('api failed', e)
  }
}
